// pages/idea/idea.js
import { createProjectService, getUserInfoService } from "../../api/project";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    user: {},
    brief: "",
    inDetail: "",
    //simplenessSkill:'',
    detailSkill: "",
    direction: "落地",
    number: "3",
    crossSchool: true,
    items: [
      {
        name: "大专",
        value: "大专",
        checked: false,
      },
      {
        name: "本科",
        value: "本科",
        checked: true,
      },
      {
        name: "研究生",
        value: "研究生",
        checked: false,
      },
    ],
    noRequirementChecked: false,
    promotionChecked: true,
    isSubmitting: false,
    isAuditStatus: null,
    isDeliveryStatus: null,
    auditPageUrl:"pages/myTeam/myTeam",
    deliveryPageUrl:"pages/myTeam/myTeam",
    // 添加登录弹窗相关数据
    showModal2: false,
    showOverlay: false,
  },

  knowTeamWay() {
    wx.navigateTo({
      url: "/pages/knowTeamWay/knowTeamWay",
    });
  },

  brief(e) {
    this.setData({
      brief: e.detail.value,
    });
    console.log(this.data.brief);
  },

  inDetail(e) {
    this.setData({
      inDetail: e.detail.value,
    });
    console.log(this.data.inDetail);
  },

  direction(e) {
    const direction = e.currentTarget.dataset.direction;
    this.setData({
      direction: direction,
    });
    console.log(this.data.direction);
  },

  number(e) {
    const number = e.currentTarget.dataset.number;
    this.setData({
      number: number,
    });
    console.log(this.data.number);
  },

  crossSchool() {
    if (this.data.crossSchool == true) {
      this.setData({
        crossSchool: false,
      });
    } else {
      this.setData({
        crossSchool: true,
      });
    }
    console.log(this.data.crossSchool ? "接受跨校" : "不接受跨校");
  },

  onRadioChange(e) {
    const selectedValue = e.detail.value;
    console.log(selectedValue);
    const updateItems = this.data.items.map((item) => {
      return {
        ...item,
        checked: item.value === selectedValue,
      };
    });
    this.setData({
      items: updateItems,
    });
  },

  onEducationChange(e) {
    const selectedValue = e.detail.value; // 单选，只有一个值
    const updateItems = this.data.items.map((item) => ({
      ...item,
      checked: item.value === selectedValue,
    }));
    this.setData({
      items: updateItems,
    });
  },


  detailSkill(e) {
    this.setData({
      detailSkill: e.detail.value,
    });
    console.log(this.data.detailSkill);
  },

  noRequirement(e) {
    this.setData({
      noRequirementChecked: e.detail.value.includes("noRequirement"),
    });
  },

  promotionChange(e) {
    this.setData({
      promotionChecked: e.detail.value,
    });
    console.log(this.data.promotionChecked ? "推广" : "不推广");
  },

  // 数据验证函数
  validateForm() {
    const {
      brief,
      inDetail,
      detailSkill,
    } = this.data;
    // 只要有一个需要校验的字段为空白，就统一提示
    if (!brief.trim() || !inDetail.trim() || !detailSkill.trim()) {
      wx.showToast({
        title: "请输入完整项目信息",
        icon: "none",
      });
      return false;
    }
    return true;
  },

  // 检查用户登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    if (!token) {
      // 显示登录模态框
      this.setData({
        showModal2: true,
        showOverlay: true,
      });
      return false;
    }
    return true;
  },
   /**
   * 处理取消登录事件
   */
  onCancelLogin() {
    this.setData({
      showModal2: false,
      showOverlay: false,
    });
  },

  // 转换数据格式以匹配后端API
  formatDataForAPI() {
    // 获取选中的学历（单选）
    const selectedItem = this.data.items.find((item) => item.checked);
    let educationRequirement = 2; // 默认本科
    if (selectedItem) {
      switch (selectedItem.value) {
        case "大专":
          educationRequirement = 1;
          break;
        case "本科":
          educationRequirement = 2;
          break;
        case "研究生":
          educationRequirement = 3;
          break;
        default:
          educationRequirement = 2;
          break;
      }
    }
    // 直接用 educationRequirement 传递即可

    // 技能要求字段，不受学习能力复选框影响
    const skillDetails = this.data.detailSkill || "无特殊要求";

    // 方向转换：根据实际的选项调整
    let directionValue = 1;
    if (this.data.direction === "落地") {
      directionValue = 1;
    } else if (this.data.direction === "获奖") {
      directionValue = 2;
    } else if (this.data.direction === "学习") {
      directionValue = 3;
    }

    return {
      projectName: this.data.brief,
      projectInfo: this.data.inDetail,
      school: this.data.user.school, // 使用默认值或根据需要设置
      direction: directionValue,
      crossSchool: this.data.crossSchool ? 1 : 0,
      educationRequirement: educationRequirement,
      skillDetails: skillDetails,
      emailPromotion: this.data.promotionChecked,
      memberCount: this.data.number, //设置默认的队伍人数
      study: this.data.noRequirementChecked, // 学习能力强复选框的状态
      isAuditStatus: this.data.isAuditStatus !== null ? this.data.isAuditStatus : false,
      isDeliveryStatus: this.data.isDeliveryStatus !== null ? this.data.isDeliveryStatus : false,
      auditPageUrl: this.data.auditPageUrl || "pages/myTeam/myTeam",
      deliveryPageUrl: this.data.deliveryPageUrl || "pages/myTeam/myTeam"
    };
  },

  // "一键快组"按钮点击事件
  quickGroup() {
    console.log("quickGroup函数被调用了");

    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return;
    }

    // 验证表单
    if (!this.validateForm()) {
      console.log("表单验证失败");
      return;
    }
    console.log("表单验证通过");

    // 防止重复提交
    if (this.data.isSubmitting) {
      return;
    }

    this.setData({
      isSubmitting: true,
    });

    // 调用send方法请求订阅消息，并等待用户选择后再发送项目创建请求
    this.send().then(() => {
      // 格式化数据
      const requestData = this.formatDataForAPI();

      console.log("项目数据:", {
        projectName: requestData.projectName,
        projectInfo: requestData.projectInfo,
        school: requestData.school,
        direction: requestData.direction,
        crossSchool: requestData.crossSchool,
        educationRequirement: requestData.educationRequirement,
        skillDetails: requestData.skillDetails,
        emailPromotion: requestData.emailPromotion,
        memberCount: requestData.memberCount,
        study: requestData.study,
        isAuditStatus: requestData.isAuditStatus,
        isDeliveryStatus: requestData.isDeliveryStatus,
        auditPageUrl: requestData.auditPageUrl,
        deliveryPageUrl: requestData.deliveryPageUrl
      });

      // 显示加载提示
      wx.showLoading({
        title: "创建中...",
        mask: true,
      });

      // 发送请求到后端
      // createProjectService(requestData)
      //   .then((res) => {
      //     console.log("请求返回的完整参数:", res);
      //     wx.hideLoading();

      //     if (res.code == 500) {
      //       //TODO 项目创建失败
      //       console.log("项目创建失败");
      //       return;
      //     }
      //     if (res.code === 200) {
      //       wx.showToast({
      //         title: "项目创建成功",
      //         icon: "success",
      //         duration: 2000,
      //         success: () => {
      //           // 延迟跳转，让用户看到成功提示
      //           setTimeout(() => {
      //             // 根据你的业务逻辑跳转到相应页面
      //             if (!requestData.emailPromotion) {
      //               wx.navigateBack({
      //                 delta: 1,
      //               });
      //               //因第二版本需要，不做删除,保留if
      //             } else if (requestData.emailPromotion === true) {
      //               // 之前是跳转到邮件推广页面，现在直接返回或仅提示成功即可
      //               wx.navigateBack({
      //                 delta: 1,
      //               });
      //             }
      //           }, 2100);
      //         },
      //       });
      //     } else {
      //       wx.showToast({
      //         title: res.message || "创建失败",
      //         icon: "none",
      //       });
      //     }
      //   })
      //   .catch((err) => {
      //     wx.hideLoading();
      //     console.error("创建失败：", err);
      //     wx.showToast({
      //       title: "网络异常，请重试",
      //       icon: "none",
      //     });
      //   })
      //   .finally(() => {
      //     this.setData({
      //       isSubmitting: false,
      //     });
      //   });

      createProjectService(requestData)
      .then((res) => {
        console.log("请求返回的完整参数:", res);
        wx.hideLoading();

        if (res.code == 500) {
          //TODO 项目创建失败
          console.log("项目创建失败");
          return;
        }
        if (res.code === 200) {
          // 使用 wx.showModal 替代 wx.showToast，确保用户能看到提示
          wx.showModal({
            title: '创建成功',
            content: '项目已成功创建',
            showCancel: false,
            confirmText: '确定',
            success: (result) => {
              // 用户点击确定后才返回上一页
              if (result.confirm) {
                // 根据你的业务逻辑跳转到相应页面
                if (!requestData.emailPromotion) {
                  wx.navigateBack({
                    delta: 1,
                  });
                } else if (requestData.emailPromotion === true) {
                  wx.navigateBack({
                    delta: 1,
                  });
                }
              }
            }
          });
        } else {
          wx.showToast({
            title: res.message || "创建失败",
            icon: "none",
          });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("创建失败：", err);
        wx.showToast({
          title: "网络异常，请重试",
          icon: "none",
        });
      })
      .finally(() => {
        this.setData({
          isSubmitting: false,
        });
      });
    }).catch(() => {
      // 如果订阅消息失败，也结束提交过程
      this.setData({
        isSubmitting: false,
      });
    });
  },

  send() {
    return new Promise((resolve) => {
      wx.requestSubscribeMessage({
        tmplIds: ['QohLW2xAWzcWsdsBkrND2ksexmY83Qz7m9ufJ3CY2aM','6ir8u8TIGHKNlrCIhmC8RPayRuqoHLnDwo3OvO3yGGs'],
        success: (res) => {
          console.log('成功', res);

          // 根据模板ID的用户选择设置对应的状态
          const auditTemplateId = 'QohLW2xAWzcWsdsBkrND2ksexmY83Qz7m9ufJ3CY2aM';
          const deliveryTemplateId = '6ir8u8TIGHKNlrCIhmC8RPayRuqoHLnDwo3OvO3yGGs';

          // 设置审核状态推送是否同意
          const isAuditAccepted = res[auditTemplateId] === 'accept';
          // 设置投递状态推送是否同意
          const isDeliveryAccepted = res[deliveryTemplateId] === 'accept';

          this.setData({
            isAuditStatus: isAuditAccepted,
            isDeliveryStatus: isDeliveryAccepted
          });

          console.log('审核状态推送设置:', this.data.isAuditStatus);
          console.log('投递状态推送设置:', this.data.isDeliveryStatus);
          resolve();
        },
        fail: (res) => {
          console.log('失败', res);
          // 用户拒绝或出现错误时，设置为false
          this.setData({
            isAuditStatus: false,
            isDeliveryStatus: false
          });

          wx.showToast({
            title: '操作取消',
            icon: 'none'
          });
          resolve(); // 注意：这里也需要resolve
        }
      });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取用户的信息
    getUserInfoService()
      .then((res) => {
        console.log(res);
        //设置成用户默认的学校
        this.setData({
          user: res.data,
        });
      })
      .catch((err) => {
        console.error("获取用户信息失败:", err);
      });
  },
  onPromotionStrategy() {
    wx.navigateTo({
      url: '/pages/promotionStrategy/promotionStrategy',
    });
  }
});
